<?php

/**
 * This is the model class for table "blog".
 *
 * The followings are the available columns in table 'blog':
 * @property string $id
 * @property string $title
 * @property string $discription
 * @property string $thumbnail
 * @property string $create_time
 * @property string $update_time
 * @property integer $category
 * @property integer $artist
 */
class Blog extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @return Blog the static model class
     */
    public $thumbnail_file;
    public $show_home;
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'blog';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('title', 'required'),
            array('category, show_home', 'numerical', 'integerOnly' => true),
            array('title, tag, thumbnail, artist', 'length', 'max' => 255),
            array('discription', 'safe'),
            //array('thumbnail', 'types'=>'jpg, gif, png, jpeg'),
            array('thumbnail_file', 'file', 'allowEmpty' => true,
                'types' => 'jpg, gif, png, jpeg',
                'maxSize' => 1024 * 1024 * 10, // 10MB
                'tooLarge' => 'The file was larger than 10MB. Please upload a smaller file.',
            ),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, tag, discription, thumbnail, create_time, update_time, category, artist', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'discription' => 'Content',
            'thumbnail' => 'Thumbnail',
            'thumbnail_file' => 'Upload Thumbnail Image',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'show_home' => 'Homepage Position',
            'category' => 'Category',
            'artist' => 'Artist',
            'tag'=> 'Tags',
        );
    }

    public function getUrl() {
        return Yii::app()->createUrl('blog/view', array('id' => $this->id, 'title' => $this->title));
    }
    public function getArtistName(){
        if($this->artist == null){
            return '';
        }
        $artist = Artist::model()->findByPk($this->artist);
        return $artist->name;
    }
    public function getCategoryName(){
        $category = BlogCategory::model()->findByPk($this->category);
        if($category != null){
            return $category->name;
        }
        return null;
    }
    public function beforeSave() {
        $this->update_time = date('Y-m-d H:i:s', time());
        $this->makeThumbName();
        return true;
    }
    public function beforeValidate() {
        if(is_array($this->artist)){
            $this->artist = implode(',', $this->artist);
        }
        return true;
    }

    public function afterSave() {
        if($this->show_home != null)
        {
            $home_model = Home::model()->findByPk($this->show_home);
            $home_model->type = 'blog';
            $home_model->owner = $this->id;
            $home_model->save();
        }
        $this->makeThumbFile();
        $this->addSearch();
    }
    public function addSearch() {
        $search_model = SearchAll::model()->findByAttributes(array('type' => 'blog', 'real_id' => $this->id));
        if ($search_model) {
            $search_model->short = $this->title;
            $search_model->save();
        }else{
            $search_model = new SearchAll;
            $search_model->short = $this->title;
            $search_model->type = 'blog';
            $search_model->real_id = $this->id;
            $search_model->save();
        }
    }
    public function beforeDelete() {
        if ($this->thumbnail != null) {
            $path_parts = pathinfo($this->thumbnail);
            $pos = strrpos($path_parts["basename"], ".");
            $ext = substr($path_parts["basename"], $pos);
            $file_name = str_replace($ext, '', $path_parts["basename"]);
            $thumb_path = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
            if (file_exists($thumb_path)) {
                unlink($thumb_path);
            }
            if (file_exists($this->thumbnail)) {
                unlink($this->thumbnail);
            }
        }
        return true;
    }

    public function makeThumbName() {
        $model = $this->model();
        $thumbnail = CUploadedFile::getInstance($model, 'thumbnail_file');
        if ($thumbnail != null) {
            $today = getdate();
            $month = $today['mon'];
            $day = $today['mday'];
            $year = $today['year'];
            $upload_path = Yii::app()->params['media_dir'] . '/' . $year . '/' . $month . '/' . $day . '/';
            $upload_name = time();
            $image_path = $upload_path . $upload_name . '.' . CUploadedFile::getInstance($model, 'thumbnail_file')->extensionName;
            $this->thumbnail = $image_path;
            if (!file_exists($upload_path)) {
                if (!Tool::mkpath($upload_path)) {
                    echo('Make directory error');
                    exit;
                }
            }
        }
    }

    public function makeThumbFile() {
        $model = $this->model();
        $thumbnail = CUploadedFile::getInstance($model, 'thumbnail_file');
        if ($thumbnail != null) {

            $thumbnail->saveAs($this->thumbnail);

            $path_parts = pathinfo($this->thumbnail);
            $pos = strrpos($path_parts["basename"], ".");
            $ext = substr($path_parts["basename"], $pos);
            $file_name = str_replace($ext, '', $path_parts["basename"]);
            $thumb = $path_parts["dirname"] . '/' . $file_name . '_thumb.' . $path_parts["extension"];
            ImageHelper::thumb(Yii::app()->params['blog_width'], Yii::app()->params['blog_height'], $this->thumbnail, array(
                        'method' => 'adaptiveResize',
                        'quality' => 90), $this->thumbnail
            );
            ImageHelper::thumb(Yii::app()->params['thumb_width'], Yii::app()->params['thumb_height'], $this->thumbnail, array(
                        'method' => 'adaptiveResize',
                        'quality' => 90), $thumb
            );
        }
    }

    public function getThumb() {
        if ($this->thumbnail != null) {
            $image_parts = pathinfo($this->thumbnail);
            return Yii::app()->baseUrl . '/' . $image_parts["dirname"] . '/' . $image_parts["filename"] . '_thumb.' . $image_parts["extension"];
        } else {
            return Yii::app()->baseUrl.'/images/no_image.jpg';
        }
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id, true);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('discription', $this->discription, true);
        $criteria->compare('thumbnail', $this->thumbnail, true);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('category', $this->category);
        $criteria->compare('artist', $this->artist);

        return new CActiveDataProvider(get_class($this), array(
            'criteria' => $criteria,
        ));
    }
}